package cc.kzc.adminauth.misc;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

import org.apache.commons.lang3.StringUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Base64Util {

	public static final String BASE64_ENCODING_CHARSET = "UTF-8";

	public static String encode(String src) {
		if (null == src) {
			return null;
		}
		byte[] textByte;
		String encodedText = null;
		try {
			textByte = src.getBytes(BASE64_ENCODING_CHARSET);
			encodedText = Base64.getEncoder().encodeToString(textByte);
		} catch (UnsupportedEncodingException e) {
			log.error("[Base64] unsupported encode <" + src + ">", e);
		}
		return encodedText;
	}

	public static String decode(String src) {
		if (null == src) {
			return null;
		}
		byte[] textByte = Base64.getDecoder().decode(src);
		String decodedText = null;
		try {
			decodedText = new String(textByte, BASE64_ENCODING_CHARSET);
		} catch (UnsupportedEncodingException e) {
			log.error("[Base64] unsupported decode <" + src + ">", e);
		}
		return decodedText;
	}
	
	public static String encodeUrlSafe(String src) {
		if (null == src) {
			return null;
		}
		byte[] textByte;
		String encodedText = null;
		try {
			textByte = src.getBytes(BASE64_ENCODING_CHARSET);
			encodedText = Base64.getUrlEncoder().encodeToString(textByte);
		} catch (UnsupportedEncodingException e) {
			log.error("[Base64] unsupported encode <" + src + ">", e);
		}
		return StringUtils.strip(encodedText, "=");
	}

	public static String decodeUrlSafe(String src) {
		if (null == src) {
			return null;
		}
		byte[] textByte = Base64.getDecoder().decode(src);
		String decodedText = null;
		try {
			decodedText = new String(textByte, BASE64_ENCODING_CHARSET);
		} catch (UnsupportedEncodingException e) {
			log.error("[Base64] unsupported decode <" + src + ">", e);
		}
		return decodedText;
	}

}
